const fs = require('fs')
const path = require('path')
const execa = require('execa')

const bin = name => path.resolve(__dirname, '../node_modules/.bin/' + name)
const run = (bin, args, opts = {}) => execa(bin, args, { stdio: 'inherit', ...opts })

const resolveVueConfigJs = appRootDir => {
  const baseConfigFilePath = path.resolve(__dirname, '../vue.config.js')
  const extendConfigFilePath = path.resolve(appRootDir, 'vue.config.js')
  if (!fs.existsSync(extendConfigFilePath)) return baseConfigFilePath
  return extendConfigFilePath
}

module.exports = {
  exec: function(appRootDir, args) {
    let cmdArgs = args
    if (typeof args === 'string') cmdArgs = [args]
    run(bin('vue-cli-service'), cmdArgs, {
      cwd: appRootDir,
      extendEnv: true,
      env: {
        VUE_CLI_SERVICE_CONFIG_PATH: resolveVueConfigJs(appRootDir)
      }
    })
  }
}
